package com.ruoyi.web.controller.api.recipe;

import com.ruoyi.common.annotation.NoLoginRequired;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.recipe.domain.RecipeCollect;
import com.ruoyi.recipe.domain.RecipeDish;
import com.ruoyi.recipe.service.IRecipeCollectService;
import com.ruoyi.recipe.service.IRecipeDishService;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.web.controller.api.APIController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

@Api("收藏")
@RestController
@RequestMapping("/api/collect")
@NoLoginRequired
public class CollectController extends APIController {

    @Autowired
    private IRecipeCollectService recipeCollectService;

    @Autowired
    private IRecipeDishService recipeDishService;

    @Autowired
    private ISysUserService userService;

    @ApiOperation("获取收藏列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "openId", value = "微信openId", required = true, dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "pageNum", value = "当前记录起始索引", dataType = "Integer", dataTypeClass = Integer.class),
            @ApiImplicitParam(name = "pageSize", value = "每页显示记录数", dataType = "Integer", dataTypeClass = Integer.class),
            @ApiImplicitParam(name = "isAsc", value = "排序方式（desc或者asc）", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "orderByColumn", value = "排序列", dataType = "String", dataTypeClass = String.class)
    })
    @PostMapping("/list")
    public TableDataInfo list(String openId) {
        if (StringUtils.isEmpty(openId)) return getDataTable(new ArrayList<RecipeCollect>());

        RecipeCollect parameterEntity = new RecipeCollect();
        parameterEntity.setOpenId(openId);

        String baseUrl = getBaseUrl();

        startPage();

        List<RecipeCollect> list = recipeCollectService.selectRecipeCollectList(parameterEntity);
        if (list != null && list.size() > 0) {
            for (RecipeCollect recipeCollect : list) {
                if (StringUtils.isNotEmpty(recipeCollect.getDishPic()) && !StringUtils.ishttp(recipeCollect.getDishPic())) {
                    String fullDishPic = baseUrl + recipeCollect.getDishPic();
                    recipeCollect.setDishPic(fullDishPic);
                }
            }
        }

        return getDataTable(list);
    }

    @ApiOperation("收藏菜品")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "openId", value = "微信openId", required = true, dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "dishId", value = "菜品Id", required = true, dataType = "Long", dataTypeClass = Long.class)
    })
    @PostMapping("/add")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult addSave(RecipeCollect entity) {
        String openId = entity.getOpenId();
        if (StringUtils.isEmpty(openId)) return error("微信openId不能为空");

        long dishId = entity.getDishId();
        if (dishId <= 0) return error("菜品Id不能为空");

        SysUser sysUser = userService.selectUserByOpenId(openId);
        if (sysUser == null) return error("用户不存在");

        RecipeDish recipeDish = recipeDishService.selectRecipeDishByDishId(dishId);
        if (recipeDish == null) return error("菜品不存在");

        //查询记录是否数据库已存在
        RecipeCollect recipeCollectParam = new RecipeCollect();
        recipeCollectParam.setUserId(sysUser.getUserId());
        recipeCollectParam.setDishId(dishId);
        List<RecipeCollect> existList = recipeCollectService.selectRecipeCollectList(recipeCollectParam);
        if (existList != null && existList.size() > 0) return success("菜品已收藏");

        RecipeCollect recipeCollect = new RecipeCollect();
        recipeCollect.setUserId(sysUser.getUserId());
        recipeCollect.setDishId(dishId);
        recipeCollect.setOpenId(openId);
        recipeCollect.setCreateBy(sysUser.getLoginName());
        int rows = recipeCollectService.insertRecipeCollect(recipeCollect);
        if (rows > 0) {
            recipeDishService.updateLikesCount(new Long[] { dishId }, 1);
            return success("收藏菜品成功");
        }
        return error("收藏菜品失败");
    }

    @ApiOperation("取消收藏菜品")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "openId", value = "微信openId", required = true, dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "dishId", value = "菜品Id", required = true, dataType = "Long", dataTypeClass = Long.class)
    })
    @PostMapping("/remove")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult removeCollect(RecipeCollect entity) {
        String openId = entity.getOpenId();
        if (StringUtils.isEmpty(openId)) return error("微信openId不能为空");

        long dishId = entity.getDishId();
        if (dishId <= 0) return error("菜品Id不能为空");

        SysUser sysUser = userService.selectUserByOpenId(openId);
        if (sysUser == null) return error("用户不存在");

        RecipeDish recipeDish = recipeDishService.selectRecipeDishByDishId(dishId);
        if (recipeDish == null) return error("菜品不存在");

        RecipeCollect recipeCollect = new RecipeCollect();
        recipeCollect.setUserId(sysUser.getUserId());
        recipeCollect.setDishId(dishId);
        recipeCollect.setOpenId(openId);
        int rows = recipeCollectService.deleteRecipeCollect(recipeCollect);
        if (rows > 0) {
            recipeDishService.updateLikesCount(new Long[] { dishId }, -1);
            return success("取消收藏菜品成功");
        }
        return error("取消收藏菜品失败");
    }
}
